/**
 * 
 */
package uni.edu.pe.analisisSentimental.dao.impl;

import static uni.edu.pe.analisisSentimental.common.Constantes.FLAG_HABILITADO;
import static uni.edu.pe.analisisSentimental.common.Constantes.FLAG_POR_PROCESAR;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;

import static uni.edu.pe.analisisSentimental.common.Constantes.*;
import uni.edu.pe.analisisSentimental.dao.UrlDAO;
import uni.edu.pe.analisisSentimental.domain.Url;

/**
 * @author nestor
 *
 */
@Repository
public class UrlDAOImpl implements UrlDAO {

    private static Logger logger = LoggerFactory.getLogger(UrlDAOImpl.class);
	private static final boolean isDebugEnabled = logger.isDebugEnabled();

	// SimpleJdbcTemplate-style...
	private SimpleJdbcTemplate simpleJdbcTemplate;

	@Autowired
	public void setDataSource(DataSource dataSource) {
	    this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
	}
	
	/*
	 * (non-Javadoc)
	 * @see uni.edu.pe.analisisSentimental.dao.UrlDAO#save(uni.edu.pe.analisisSentimental.domain.Url)
	 */
	public void save(Url url) {		
		logger.debug("<==== Inicio save ====>");	
		if(isDebugEnabled)
			logger.debug("url: "+ToStringBuilder.reflectionToString(url));
		String sql =  "INSERT INTO URL (IdTweet, UrlCorta, UrlLarga, UrlMostrada,FlagEnProceso)"+
	    "VALUES(:idTweet, :urlCorta, :urlLarga, :urlMostrada, :flagEnProceso)";
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("idTweet", url.getIdTweet());
		parameters.put("urlCorta", url.getUrlCorta());
		parameters.put("urlLarga", url.getUrlLarga());
		parameters.put("urlMostrada", url.getUrlMostrada());
		parameters.put("flagEnProceso", url.getFlagEnProceso());
		simpleJdbcTemplate.update(sql,parameters);	
		
	}

	/*
	 * (non-Javadoc)
	 * @see uni.edu.pe.analisisSentimental.dao.UrlDAO#saveAll(java.util.List)
	 */
	public void saveAll(List<Url> urls) {
		logger.debug("<==== Inicio saveAll ====>");
		if(CollectionUtils.isNotEmpty(urls)){
			for(Url um: urls){
				save(um);
			}
		}
		
	}

	/*
	 * (non-Javadoc)
	 * @see uni.edu.pe.analisisSentimental.dao.UrlDAO#obtenerUrlsPorProcesar()
	 */
	public List<Url> obtenerUrlsPorProcesar(String codFinData) {
		logger.debug("<==== Inicio Method obtenerUrlsPorProcesar ====>");
		String sql = "SELECT url.Id, url.Idtweet, url.UrlCorta, url.UrlMostrada  " +
					"FROM tweets_procesados tp " +
					"INNER JOIN status_tweet st " +
					"ON tp.IdTweet=st.IdTweet " +
					"INNER JOIN URL url "+
					"ON st.idtweet = url.idtweet "+
					"where  url.FlagEnProceso = :flagEnProceso "+
					"and st.CodFinalidadData=:codFinalidadData "+
					"and tp.CodFaseTwitter=:codFaseTwitter " +
					"and tp.CodOpinionTwitter = :codOpinionTwitter";
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("flagEnProceso", FLAG_POR_PROCESAR);
		parameters.put("codFinalidadData", codFinData);
		parameters.put("codFaseTwitter", COD_FASE_ANALISIS_SUBJETIVIDAD_RM_1);
		parameters.put("codOpinionTwitter", COD_OPINION_OBJETIVA);

		 RowMapper<Url> mapper = new RowMapper<Url>() {  
		        public Url mapRow(ResultSet rs, int rowNum) throws SQLException {
		        	Url st = new Url();
		        	st.setId(rs.getInt("Id"));
		            st.setIdTweet(rs.getLong("IdTweet"));
		            st.setUrlCorta(rs.getString("UrlCorta"));	
		            st.setUrlMostrada(rs.getString("UrlMostrada"));	
		            return st;
		        }
		    };

	    return this.simpleJdbcTemplate.query(sql, mapper, parameters);
		
	}

	/*
	 * (non-Javadoc)
	 * @see uni.edu.pe.analisisSentimental.dao.UrlDAO#actualizarUrlBatch(java.util.List)
	 */
	public int[] actualizarFlagDeProcesoUrlBatch(List<Url> ltpUrl) {
		logger.debug("<==== Inicio Method actualizarUrlBatch ====>");
		int[] updateCounts = null;
		if(CollectionUtils.isNotEmpty(ltpUrl)){
			int size = ltpUrl.size();
			Map[] mapUrl = new Map[size];
			for(int i=0;i<size;i++){
				Url tp = ltpUrl.get(i);
				Map<String, Object> parameters = new HashMap<String, Object>();
				parameters.put("id", tp.getId());
				parameters.put("flagEnProceso", FLAG_HABILITADO);
				mapUrl[i]=parameters;
			}
			SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(mapUrl);
			String sql =  "UPDATE URL set FlagEnProceso=:flagEnProceso where Id=:id";
			updateCounts = simpleJdbcTemplate.batchUpdate(sql,batch);	
			mapUrl =null;
			batch=null;
		}

		return updateCounts;
		
	}

}
